package com.qf.business.user.core.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.business.user.core.dao.SysRoleDao;
import com.qf.business.user.core.service.SysRolePowerService;
import com.qf.business.user.core.service.SysRoleService;
import com.qf.data.user.dto.SysRoleCheckDto;
import com.qf.data.user.entity.SysRole;
import com.qf.data.user.entity.SysRolePower;
import com.qf.data.user.vo.input.SysSetRolePowerInput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色表(SysRole)表服务实现类
 *
 * @author makejava
 * @since 2022-08-31 14:11:07
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRole> implements SysRoleService {

    /**
     * 角色 - 权限中间表的操作Service
     */
    @Autowired
    private SysRolePowerService sysRolePowerService;

    /**
     * 设置指定角色的权限列表
     * @param rolePowerInput
     * @return
     */
    @Override
    @Transactional
    public int updateRolePowers(SysSetRolePowerInput rolePowerInput) {

        // SysSetRolePowerInput( rid: 1, pids: [1,4,5,7,8])
        // List<SysRolePower> - [{rid:1, powid:1}, {rid:1, powid:4}, {rid:1, powid:5}...]

        //根据角色id，删除原来的角色和权限的关联信息
        sysRolePowerService.deleteByRid(rolePowerInput.getRid());

        if (CollectionUtils.isEmpty(rolePowerInput.getPids())) return 0;

        List<SysRolePower> rolePowers = rolePowerInput.getPids().stream()
                .map(pid -> {
                    SysRolePower sysRolePower = new SysRolePower();
                    sysRolePower.setRid(rolePowerInput.getRid());
                    sysRolePower.setPowid(pid);
                    return sysRolePower;
                }).collect(Collectors.toList());

        //批量保存
        sysRolePowerService.saveBatch(rolePowers);
        return 1;
    }

    public static void main(String[] args) {
        List<Integer> as = new ArrayList<>();
        as.add(1);
        as.add(3);
        as.add(4);
        as.add(5);
        as.add(6);

        List<String> result = as.stream().map(integer -> integer + "后缀").collect(Collectors.toList());

        System.out.println("stream流之后的list:" + result);
    }

    /**
     * 根据用户id，查询角色列表 以及 当前用户是否拥有当前的角色
     * @param uid
     * @return
     */
    @Override
    public List<SysRoleCheckDto> queryRolesByUid(Integer uid) {
        return getBaseMapper().queryRolesByUid(uid);
    }

}

